package com.dao;

import com.model.Order;
import com.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderDAO {
    Connection conn = null;
    PreparedStatement pstmt= null;
    ResultSet rs = null;
    int  twe=0;
    public List<Order> getAllorder01() {

        List<Order> orderList =new ArrayList<>();
        try {
            conn = JDBCUtil.getCon();
            String sql = "select product_id, quantity,total_price from orders";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                Order order = new Order();
                order.setProductId(rs.getInt("product_id"));
                order.setQuantity(rs.getInt("quantity"));
                order.setTotalPrice(rs.getDouble("total_price"));

                orderList.add(order);
            }
            for (Order order1 : orderList) {
                System.out.println(order1);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                JDBCUtil.colse(rs, pstmt, conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return orderList;
    }
    public void createOrder(Order order) {

        try (Connection conn = JDBCUtil.getCon();
             PreparedStatement stmt = conn.prepareStatement("INSERT INTO orders (product_id, quantity, total_price) VALUES (?, ?, ?)", PreparedStatement.RETURN_GENERATED_KEYS)) {
            stmt.setInt(1, order.getProductId());
            stmt.setInt(2, order.getQuantity());
            stmt.setDouble(3, order.getTotalPrice());
            stmt.executeUpdate();

            try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    order.setId(generatedKeys.getInt(1));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
